﻿Imports System.Web.UI
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Configuration
Imports System.Net.Mail


Partial Public Class Wfrm_Despacha_OrdenCompra
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Carga_Grilla_OC()
            FPago()
        End If
    End Sub
    'Sub Carga_Datos_Usuario()
    '    Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
    '    Dim rp As New DotNetResponse.SQLPersistence
    '    rp.StoredProcedure = "SP_OC_Get_INFO_FORM"
    '    rp.AddParametro(ViewState("usu"))
    '    exec.ExecuteDataTable(rp)

    '    If rp.TieneDatos Then
    '        lbl_clinica.Text = rp.DtTable.Rows(0).Item("tNombreFantasia").ToString.Trim
    '        lbl_usuario.Text = rp.DtTable.Rows(0).Item("Tnombre").ToString.Trim
    '        lbl_fecha.Text = Now

    '        lbl_clinica.UpdateAfterCallBack = True
    '        lbl_usuario.UpdateAfterCallBack = True
    '        lbl_fecha.UpdateAfterCallBack = True

    '    End If

    'End Sub

    Sub FPago()

        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_GET_FPAGOS"

        exec.ExecuteDataTable(rp)
        cmb_forma_pago.DataTextField = "tdescripcion"
        cmb_forma_pago.DataValueField = "ncodigo_pki"
        cmb_forma_pago.DataSource = rp.DtTable
        cmb_forma_pago.DataBind()
        cmb_forma_pago.UpdateAfterCallBack = True


    End Sub
    Sub Mensaje(ByVal Mensaje As String)
        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & Mensaje & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & Mensaje & "')</script>")
        End If
    End Sub


    Sub Carga_Grilla_OC()
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_GET_ORDEN_COMPRA_GENERADA"
        exec.ExecuteDataTable(rp)
        Grilla_OC.DataSource = rp.DtTable
        Grilla_OC.DataBind()
        Grilla_OC.UpdateAfterCallBack = True


    End Sub
    Sub Carga_Productos(ByVal id_oc As String)
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_GET_PRODUCTOS_ORDEN_COMPRA"
        rp.AddParametro(id_oc)
        exec.ExecuteDataTable(rp)
        Grilla_SOL.DataSource = rp.DtTable
        Grilla_SOL.DataBind()
        Grilla_SOL.UpdateAfterCallBack = True
    End Sub
    Protected Sub img_imprimir_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_imprimir.Click
        If Not aCTUALIZA_dESPACHO() Then

            Exit Sub
        End If


        Dim rp As New Rpt_OrdenCompra

        Dim _CRConnectionInfo As ConnectionInfo

        _CRConnectionInfo = New ConnectionInfo()
        _CRConnectionInfo.ServerName = ConfigurationManager.AppSettings("cnn_server") '"application.dyndns-web.com"
        _CRConnectionInfo.DatabaseName = ConfigurationManager.AppSettings("cnn_database") '"comprasFarm"
        _CRConnectionInfo.UserID = ConfigurationManager.AppSettings("cnn_userid") '"lilas"
        _CRConnectionInfo.Password = ConfigurationManager.AppSettings("cnn_password") '"lilas"

        Dim tables As Tables
        tables = rp.Database.Tables
        For i = 0 To tables.Count - 1
            Dim tableLogonInfo As TableLogOnInfo = tables(i).LogOnInfo
            tableLogonInfo.ConnectionInfo = _CRConnectionInfo
            tables(i).ApplyLogOnInfo(tableLogonInfo)
        Next

        rp.SetParameterValue(0, lbl_nro_oc.Text)
        'rp.SetParameterValue(1, lbl_nro_oc.Text)


        'Dim tables2 As Tables
        'tables2 = rp.Subreports(0).Database.Tables
        'For i = 0 To tables2.Count - 1
        '    Dim tableLogonInfo As TableLogOnInfo = tables2(i).LogOnInfo
        '    tableLogonInfo.ConnectionInfo = _CRConnectionInfo
        '    tables2(i).ApplyLogOnInfo(tableLogonInfo)
        'Next

        'rp.Subreports(0).SetParameterValue("@OC_1", ViewState("id_oc"))
        'rp.Subreports(0).SetParameterValue(0, 17)
        DESPACHO_DB(lbl_nro_oc.Text)

        rp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Page.Response, True, "OrdenCompra_" & lbl_nro_oc.Text & ".pdf")
        'rp.ExportToDisk (ExportFormatType.PortableDocFormat ,"")


    End Sub
    Function aCTUALIZA_dESPACHO()
        'If Not IsDate(datepicker.Text) Then
        '    Mensaje("Falta ingresar Fecha Despacho")
        '    Return False
        'End If

        Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim RpE As New DotNetResponse.SQLPersistence
        RpE.StoredProcedure = "SP_OC_UPDATE_OC_DESPACHO"
        RpE.AddParametro(lbl_nro_oc.Text)
        RpE.AddParametro(datepicker.Text)
        RpE.AddParametro(cmb_forma_pago.SelectedValue)
        Exec.ExecuteNonQuery(RpE)
        Exec.Commit()

        Return True

    End Function
    Sub DESPACHO_DB(ByVal ID_OC As String)
        Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim RpE As New DotNetResponse.SQLPersistence
        RpE.StoredProcedure = "SP_OC_UPDATE_ENVIAR_OC"
        RpE.AddParametro(ID_OC)
        Exec.ExecuteNonQuery(RpE)
        Exec.Commit()

        If Not RpE.Errores Then
            Carga_Grilla_OC()
            Carga_Productos(0)

            'img_Despachar.Enabled = False
            'img_imprimir.Enabled = False

            'img_Despachar.UpdateAfterCallBack = True
            'img_imprimir.UpdateAfterCallBack = True

        Else
            Mensaje(RpE.MensajeError)
            
        End If


    End Sub
    Protected Sub lnk_despachar_Click(ByVal sender As Object, ByVal e As EventArgs)

    End Sub

    Protected Sub Grilla_OC_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Grilla_OC.SelectedIndexChanged
        lbl_proveedor.Text = Grilla_OC.SelectedItem.Cells(4).Text
        lbl_proveedor.UpdateAfterCallBack = True
        lbl_nro_oc.Text = Grilla_OC.SelectedItem.Cells(3).Text
        lbl_nro_oc.UpdateAfterCallBack = True

        Carga_Productos(Grilla_OC.SelectedItem.Cells(3).Text)

        img_Despachar.Visible = True
        img_imprimir.Visible = True
        img_imprimir.UpdateAfterCallBack = True
        img_Despachar.UpdateAfterCallBack = True

        datepicker.Text = ""
        lblfecha.Visible = True
        datepicker.Visible = True
        lblformaPago.Visible = True
        cmb_forma_pago.Visible = True

        lblfecha.UpdateAfterCallBack = True
        datepicker.UpdateAfterCallBack = True
        lblformaPago.UpdateAfterCallBack = True
        cmb_forma_pago.UpdateAfterCallBack = True


        Anthem.Manager.AddScriptForClientSideEval(" $('#datepicker').datepicker({ changeYear: true, changeMonth: true });")


    End Sub
    Sub Cargar_Datos_Despacho()
        Dim Exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Rp.StoredProcedure = "SP_OC_GET_Datos_Despacho"
        Rp.AddParametro(Grilla_OC.SelectedItem.Cells(6).Text)
        Exec.ExecuteDataTable(Rp)
        If Rp.TieneDatos Then
            txt_asunto.Text = Rp.DtTable.Rows(0).Item("Subject")
            txt_destinatario.Text = Rp.DtTable.Rows(0).Item("email_destinatario") '.ToString()
            txt_destinatario.UpdateAfterCallBack = True
            txt_mensaje.Text = Rp.DtTable.Rows(0).Item("Body")
        End If

    End Sub
    Protected Sub img_Despachar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_Despachar.Click
        If Not aCTUALIZA_dESPACHO() Then
            Exit Sub
        End If

        lblSolicitud2.Text = "N° Orden de Compra : " & Grilla_OC.SelectedItem.Cells(3).Text
        lblSolicitud2.UpdateAfterCallBack = True

        Cargar_Datos_Despacho()

        'Clinica xxxxx - OC NN
        txt_asunto.Text = "OC N° " & Grilla_OC.SelectedItem.Cells(3).Text
        txt_mensaje.Text = "Se adjunta detalle de Orden de Compra. Favor confirmar recepción y fecha de despacho."
        txt_asunto.UpdateAfterCallBack = True
        txt_mensaje.UpdateAfterCallBack = True


        Anthem.Manager.AddScriptForClientSideEval("document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'")
    End Sub

    Protected Sub img_Despachar0_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_Despachar0.Click
        Try
            Dim emails() As String = txt_destinatario.Text.Trim.Split(",")
            Dim ii As Integer
            For ii = 0 To emails.Length - 1
                If Not DotNetDal.Generica.ValidaEmail(emails(ii)) Then
                    Mensaje("Email inválido : " & emails(ii))                   
                    Exit Sub
                End If
            Next


            'If Not DotNetDal.Generica.ValidaEmail(txt_destinatario.Text.Trim) Then
            '    Mensaje("Email inválido")
            '    Exit Sub
            'End If

            Dim rep As New Rpt_OrdenCompra
            Dim _CRConnectionInfo As ConnectionInfo

            _CRConnectionInfo = New ConnectionInfo()
            _CRConnectionInfo.ServerName = ConfigurationManager.AppSettings("cnn_server") '"application.dyndns-web.com"
            _CRConnectionInfo.DatabaseName = ConfigurationManager.AppSettings("cnn_database") '"comprasFarm"
            _CRConnectionInfo.UserID = ConfigurationManager.AppSettings("cnn_userid") '"lilas"
            _CRConnectionInfo.Password = ConfigurationManager.AppSettings("cnn_password") '"lilas"

            Dim tables As Tables
            tables = rep.Database.Tables
            For i = 0 To tables.Count - 1
                Dim tableLogonInfo As TableLogOnInfo = tables(i).LogOnInfo
                tableLogonInfo.ConnectionInfo = _CRConnectionInfo
                tables(i).ApplyLogOnInfo(tableLogonInfo)
            Next

            rep.SetParameterValue(0, lbl_nro_oc.Text)
            'rep.SetParameterValue(1, lbl_nro_oc.Text)

            'Dim tables2 As Tables
            'tables2 = rep.Subreports(0).Database.Tables
            'For i = 0 To tables2.Count - 1
            '    Dim tableLogonInfo As TableLogOnInfo = tables2(i).LogOnInfo
            '    tableLogonInfo.ConnectionInfo = _CRConnectionInfo
            '    tables2(i).ApplyLogOnInfo(tableLogonInfo)
            'Next

            'rp.Subreports(0).SetParameterValue("@OC_1", ViewState("id_oc"))
            'rp.Subreports(0).SetParameterValue(0, 17)
            Dim Ruta_PDF As String = ConfigurationManager.AppSettings("ruta_rpt") & "OrdenCompra_" & lbl_nro_oc.Text & ".pdf"
            'rp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Page.Response, True, "OrdenCompra_" & Grilla_OC.SelectedItem.Cells(3).Text & ".pdf")
            rep.ExportToDisk(ExportFormatType.PortableDocFormat, Ruta_PDF)

            Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
            Dim Rp As New DotNetResponse.SQLPersistence
            '
            'ID_oc
            Dim EmailCC As String = ""

            Rp.StoredProcedure = "SP_GET_EMAIL_CLINICA"
            Rp.AddParametro(Val(lbl_nro_oc.Text))
            Exec.ExecuteDataTable(Rp)
            If Not Rp.TieneDatos Then
                Mensaje("OC no encontrada")
                Exec.Rollback()
                Exit Sub
            Else
                If Rp.DtTable.Rows(0).Item(0).ToString.Length = 0 Then
                    Mensaje("Email no registrado")
                    Exec.Rollback()
                    Exit Sub
                Else
                    If Not DotNetDal.Generica.ValidaEmail(Rp.DtTable.Rows(0).Item(0).ToString) Then
                        Mensaje("Email inválido : " & Rp.DtTable.Rows(0).Item(0).ToString)
                        Exit Sub
                    End If
                End If
            End If
            EmailCC = Rp.DtTable.Rows(0).Item(0).ToString
            txt_asunto.Text = Rp.DtTable.Rows(0).Item(1).ToString() & " " & txt_asunto.Text.Trim


            Rp.ClearParametro()
            Rp.StoredProcedure = "SP_OC_SAVE_Datos_Despacho"
            Rp.AddParametro(Grilla_OC.SelectedItem.Cells(6).Text)
            Rp.AddParametro(txt_asunto.Text.Trim)
            Rp.AddParametro(txt_destinatario.Text.Trim)
            Rp.AddParametro(txt_mensaje.Text.Trim)
            Exec.ExecuteNonQuery(Rp)

            If Rp.Errores Then
                Mensaje(Rp.MensajeError)
            Else
                'enviar email
                'For ii = 0 To emails.Length - 1
                SendMail(Rp, txt_destinatario.Text.Trim, txt_mensaje.Text.Trim, txt_asunto.Text.Trim, Ruta_PDF, ConfigurationManager.AppSettings("mail_CC") & "," & EmailCC)
                'Next
            End If

            If Rp.Errores Then
                Mensaje(Rp.MensajeError)
                Exec.Rollback()
                Exit Sub
            End If

            Exec.Commit()
            DESPACHO_DB(lbl_nro_oc.Text)

            'Anthem.Manager.AddScriptForClientSideEval("document.getElementById('light').style.display='hidden';document.getElementById('fade').style.display='hidden'")

            Mensaje("Orden de Compra Despachada Exitosamente")

        Catch ex As Exception
            Mensaje(ex.Message)
        End Try

    End Sub
    Sub SendMail(ByRef rp As DotNetResponse.SQLPersistence, ByVal mail_destino As String, ByVal Body As String, ByVal subject As String, ByVal Archivo As String, ByVal Email_CC As String)
        Try
            Dim Mail As MailMessage
            Dim SmtpServer As New SmtpClient()
            SmtpServer.Credentials = New Net.NetworkCredential(ConfigurationManager.AppSettings("mail_credencial_login"), ConfigurationManager.AppSettings("mail_credencial_clave")) 'WebConfig
            SmtpServer.Port = 25
            SmtpServer.Host = ConfigurationManager.AppSettings("mail_credencial_servidor")
            'SmtpServer.EnableSsl = True
            Mail = New MailMessage()
            Try
                Mail.From = New MailAddress(ConfigurationManager.AppSettings("mail_email_origen"), ConfigurationManager.AppSettings("mail_nombre_origen"), System.Text.Encoding.UTF8) 'WebConfig
                Mail.Subject = subject

                If Archivo.Length > 0 Then
                    Dim item As New System.Net.Mail.Attachment(Archivo)
                    Mail.Attachments.Add(item)
                End If
                Mail.To.Add(mail_destino)
                If Not Email_CC Is Nothing Then
                    Mail.CC.Add(Email_CC)
                End If

                Mail.Body = Body

                SmtpServer.Send(Mail)
            Catch ex As Exception
                rp.Errores = True
                rp.MensajeError = ex.Message
            End Try

        Catch ex As Exception
            rp.Errores = True
            rp.MensajeError = ex.Message
        End Try

    End Sub

    Protected Sub Eliminar0_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
          Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_DEL_ORDEN_COMPRA"
        rp.AddParametro(DirectCast(sender.parent.parent, DataGridItem).Cells(3).Text)
        exec.ExecuteNonQuery(rp)
        exec.Commit()

        If Not rp.Errores Then
            Carga_Grilla_OC()          
        End If

        img_imprimir.Visible = False
        img_Despachar.Visible = False
        img_Despachar.UpdateAfterCallBack = True
        img_imprimir.UpdateAfterCallBack = True
    End Sub

    Protected Sub btnBuscaSol_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBuscaSol.Click
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_GET_ORDEN_COMPRA_GENERADA_ENVIADA"
        rp.AddParametro(Val(txtNOC.Text))
        exec.ExecuteDataTable(rp)
        If rp.TieneDatos Then
            Grilla_OC.DataSource = rp.DtTable
            Grilla_OC.DataBind()
            Grilla_OC.UpdateAfterCallBack = True
        Else
            Mensaje("Orden de Compra No encontrada")
        End If
        
    End Sub
End Class